<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use think\Db;
use think\Validate;

/**
 * 获取表
 * @return [type]
 */
//function getTable($username)
//{
//	return 'info' . (abs(crc32($username)) % 9);
//}
/*------------------验证码--------------------*/

function yam($zhi)
{
	$PUBKEY = "780ee853-300e-4f63-84f1-66b32ba16a88";
    $PRIKEY = "817f809d-04af-4813-a62f-ecd51d419e60";
    $touclick = new TouClick($PUBKEY,$PRIKEY);
    $res = $touclick->check($zhi['sid'], $zhi['checkAddress'], $zhi['token']);
    if ($res['message'] == '验证成功') {
        return true;
    }else{
    	return FALSE;
	}
}
/*---------------验证是否为VIP--------------------*/
function is_vip($id=0)
{
	$user = json_decode(cookie('fuchen_user'),true);
	if(isset($user['password']) && isset($user['id']))
	{
		if(get_token($user['id'])==$user['password']){
			$vip=Db::name('user')->field('vip')->where('id',$user['id'])->cache('mark',600)->find();
			if($vip['vip']!=null && $vip['vip']!='null'){
				return true;
			}else{
				return FALSE;
			}
		}else{
			return FALSE;
		}
	}else{
		return FALSE;
	}
	
	
	

}
//------------------推广积分-----------------------
function spreadmark($id,$ip){
	if(preg_match('/^[0-9]{1,30}$/', $id)){
		$filename = "markip".$id;
		$redis = new \Redis();
		$redis->connect('127.0.0.1',6379);
		$redis->auth('ruqingnimabi');
		$redis->select(1);
		$over=$redis->Sismember($filename,$ip);
		if(!$over){
			$redis->sadd($filename,$ip);
			$v=Db::query('select mark from user where id='.$id);
		    $num=$v[0]['mark']+1;
		    Db::execute('update user set mark='.$num.' where id='.$id);
		}
	}
}

//验证登lu

function validatelogin($zhi){
	Validate::extend('letterandnum', function($value){
	return (bool) preg_match('/^[0-9a-zA-Z]{1,30}$/', $value);
	});

	$validate = new Validate([
		'user'		=>	'letterandnum|max:25',
		'password'  =>	'letterandnum|max:25'
	], [
		'user.letterandnum'	=>	'只能是数字和字母组合',
		'password.letterandnum'	=>	'只能是数字和字母组合'
	]);
		if($zhi['type']=="登录"){
			$myconnect=model('User');
			$over=$myconnect->where('username',$zhi['user'])->find();
			if($zhi['password']==$over['password']){
				$keynum=chr(mt_rand(97,122)).mt_rand(100000, 999999999).chr(mt_rand(65, 90));
				set_token($over['id'],$keynum);
				$over['password']=$keynum;
				if($over['vip']!=null){
					$guoqi=date_diff(date_create($over['vip']),date_create(date('Y-m-d')));
				    if($guoqi->format('%R%a')>=0){
					$over['vip']='null';
					$myconnect->where('username',$zhi['user'])->update(['vip'=>null]);
				}
				}
				return $over;
			}else{
				return "账户名或密码错误!";
			}
		}elseif($zhi['type']=="注册"){
			$myconnect=model('User');
			 if ($validate->check($zhi)){
			 	$over=$myconnect->where('username',$zhi['user'])->find();
				 if(!$over){
				 	$myconnect->save([
					'username'	=>	$zhi['user'],
					'password'	=>	$zhi['password']
				    ]);
					mkdir("../static/userip/".$myconnect->id,0777);
					chmod("../static/userip/".$myconnect->id,0777);
				    $filename = "../static/userip/".$myconnect->id.'/'.$myconnect->id.'.txt';
				    $handle=fopen($filename, 'w');
				    fclose($handle);
					$filename = "../static/userip/".$myconnect->id.'/markip.txt';
					$handle=fopen($filename, 'w');
				    fclose($handle);
					return "注册成功，请登录！";
				}else{
					return "此用户名已存在！";
				}
			 }else{
			  return $validate->getError();

			 }


		}else{
			return "请求非法！";
		}

}

//存储获取信息
function setExt($id,$ip)
{
	$zhi = new stdClass();
	$zhi -> ip = $ip;
	$zhi -> datetime = time();
	$zhi = json_encode($zhi);
 	$redis = new \Redis();
    $redis->connect('127.0.0.1',6379);
	$redis->auth('ruqingnimabi');
    $redis -> lpush('ip'.$id,$zhi);
}

function get_place($id)
{
	$redis = new \Redis();
	$redis->connect('127.0.0.1',6379);
	$redis->auth('ruqingnimabi');
	$str=$redis->lrange('ip'.$id,0,36);
	return $str;
}

//-----------卡密充值-------------------
function findcard($card){//验证卡密是否存在
   $zhi=Db::name('vipcard')->where('card',$card)->find();
   if(isset($zhi['type'])){
	   return $zhi['type'];
   }else{
   	   return 0;
   }
}

function updatevip($id,$card){//升级VIP用户
	$cardtype=findcard($card);
	if($cardtype){
		switch ($cardtype){
			case 1:
				$viptime=1;
				break;
			case 2:
				$viptime=3;
				break;
			case 3:
				$viptime=120;
				break;
		}
		$zhi=Db::name('user')->field('vip')->where('id',$id)->find();
		if($zhi['vip']==null || $zhi['vip']=='0000-00-00'){
			$date=date('Y-m-d',strtotime('+'.$viptime.'month'));
		}else{
			$date=date('Y-m-d',strtotime($zhi["vip"].'+'.$viptime.'month'));
		}
		$zhi=Db::execute("update user set vip='".$date."' where id=".$id.";");
		if($zhi){
			Db::name('vipcard')->where('card',$card)->delete();
			return Db::name('user')->field('vip')->where('id',$id)->find();
		}else{
			return '请求失败，请重试！';
		}
	}else{
		return '卡密不存在~请重新输入!';
	}

}

function recordvip($id,$card){//卡密兑换记录
	$filename=APP_PATH.'admin/vipcard/'.date('Y');
	if(is_dir($filename)!=TRUE){
		mkdir($filename);
	}
	$filename=$filename.'/'.date('m').'.txt';
	$ip = (string) request()->server('REMOTE_ADDR');
	$data=date('Y-m-d H:m---').$id.'---'.$card.'---'.$ip.'\n';
	file_put_contents($filename, $data,FILE_APPEND);
}

//----------------积分刷新获取---------------------
function mark($id){
	return Db::name('user')->field('mark')->where('id',$id)->cache('mark',60)->find();
}
//---------------添加任务--------------------------
function query_auto_add($id,$str)
{
	if(is_vip()){
		$redis=new \Redis();
		$redis->connect('127.0.0.1',6379);
		$redis->auth('ruqingnimabi');
		$bol=$redis->sadd('quser',$id);
		if($bol){
			$redis->set('query:'.$id,serialize($str));
			$redis->lpush('result:'.$id,$str["sign"]);
			return '添加完毕，正在处理中，请耐心等待.....';
		}else{
			return '添加失败，您有任务正在查询~请查询完毕后重试！';
		}
	}else{
		return '本功能为VIP功能！';
	}


}
//--------------取出任务ID-----------------------
function query_auto_get()
{
	$redis = new \Redis();
	$redis->connect('127.0.0.1',6379);
	$redis->auth('ruqingnimabi');
	return $redis->smembers('quser');
}
//-------------取出任务数据------------------------
function query_auto_data($id)
{
	$redis = new \Redis();
	$redis->connect('127.0.0.1',6379);
	$redis->auth('ruqingnimabi');
	$data = $redis->get('query:'.$id);
	$data = unserialize($data);
	return $data;
}

//-------------保存查询的数据--------------------
function query_auto_save($id,$sign,$data)
{
	$filename = ROOT_PATH. 'static/userip/'.$id.'/'.iconv('UTF-8', 'GBK', $sign).'.txt';
	file_put_contents($filename, $data);
	$redis = new \Redis();
	$redis->connect('127.0.0.1',6379);
	$redis->auth('ruqingnimabi');
	$redis->lset('result:'.$id,0,$sign.'|true');
	$redis->srem('quser',$id);
}
//-------------用户端任务列表显示------------
function query_auto_show($id,$num)
{
	$redis = new \Redis();
	$redis->connect('127.0.0.1',6379);
	$redis->auth('ruqingnimabi');
	$data = $redis->lrange('result:'.$id,$num,$num+9);
	return $data;
}
//------------引擎模式-------------
function search_engines($data,$id)
{
	if(is_vip()){
		$str =rawurlencode('"'.$data['value'].'"');
		$header=array('User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36','Referer:https://a363.firstguo.com','Host:a363.firstguo.com');
		if($data['wbe']!=''){
			$str = 'site:'.$data['wbe'].'+'.$str;
		}
		
		//return 'https://a363.firstguo.com/search?q='.$str.'&lr=lang_zh-CN&tbs=lr:lang_1zh-CN&start='.$data['page'];
		
		$result=curl('https://a363.firstguo.com/search?q='.$str.'&lr=lang_zh-CN&tbs=lr:lang_1zh-CN&start='.$data['page'],'GET',$se,true,false,$header);
		$pattern = '/<h3 class="r">([\s\S]*?)<\/h3>/i';
		preg_match_all($pattern,$result,$arr);
		return $arr[1];
	}else{
		return 9;
	}
}

//--------获取网盘真实用户名--------------
function pan_user($uk)
{
	if($uk == 0) return ;
	$json = curl("http://pan.baidu.com/pcloud/user/getinfo?bdstoken=null&query_uk={$uk}&t=1466321382258&channel=chunlei&clienttype=0&web=1");
	$json = json_decode($json,true);
	if(isset($json['user_info']['uname'])){
		return '百度网盘真实用户名为' . $json['user_info']['uname'];
	}else{
		return '查询失败了！请检查链接是否正确！';
	}
	
}

//-------保存QQcookies---------------
function qq_cookies_save($sign,$data)
{
	$vip=Db::name('user')->field('vip')->where('id',$sign)->cache('mark',600)->find();
	if($vip['vip']!=null && $vip['vip']!='null'){
		$now = time();
		Db::execute("insert into qq(sign,cookies,gettime) value('{$sign}','{$data}','{$now}');");
	}
	
}

function qq_cookies_get($sign,$offset)
{
	return Db::query("select * from qq where sign='{$sign}' limit {$offset},10");
}

function fuchen_key($id,$key)
{
	$token = get_token($id);
	if($token == $key){
		
		$vip=Db::name('user')->field('vip')->where('id',$id)->cache('mark',600)->find();
		if($vip['vip']!=null && $vip['vip']!='null'){
			return client_json();
		}else{
			return -1;
		}
		
	}else{
		return 0;
	}
}

function client_json()
{
	$filename = ROOT_PATH. 'static/email.json';
	$str0 = file_get_contents($filename);
	$filename = ROOT_PATH. 'static/phone.json';
	$str1 = file_get_contents($filename);
	$response = "{\"email\":$str0,\"phone\":$str1}";
	return $response;
}

function clear_qq($sign)
{
	$now = time()-3600;
	Db::execute("delete from qq where sign='$sign' and gettime<'$now';");
	
}

//------------网页公告------------------
function notice_get()
{
	$redis = new \Redis();
	$redis->connect('127.0.0.1',6379);
	$redis->auth('ruqingnimabi');
	return $redis -> get('notice');
}























































































































































































/**
* curl模拟提交
* @param        string                        $url                网址
* @param        array/string        $opt                提交参数
* @param        string                        &$header        取回的头信息
* @param        string                        $redirect        是否重定向
* @param        boolean                        $ssl                验证https证书
* @return        [type]                                                返回信息
*/
function curl($url, $opt='GET', &$header=null, $redirect=true, $ssl=false,$set_header=[]){

        //初始化
        $ch = curl_init($url);

        //配置设置
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $ssl);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $ssl);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $redirect);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                #返回结果
        curl_setopt($ch, CURLOPT_HEADER, true);                               #显示协议头
		curl_setopt($ch, CURLOPT_HTTPHEADER,$set_header);
        if(is_array($opt)){

                //转小写
                $opt = array_change_key_case($opt, CASE_LOWER);

                //POST
                if(isset($opt['type']) && strtoupper($opt['type'])=='POST'){
                        curl_setopt($ch, CURLOPT_POST, true);
                        curl_setopt($ch, CURLOPT_POSTFIELDS, (isset($opt['data']) ? $opt['data'] : ''));
                }

                //User-Agent
                if(array_key_exists('ua', $opt))
                        curl_setopt($ch, CURLOPT_USERAGENT, $opt['ua']);

                //Header
                if(array_key_exists('header', $opt)){
                        curl_setopt($ch, CURLOPT_HTTPHEADER, (array)$opt['header']);
                }

                //Cookie
                if(array_key_exists('cookie', $opt))
                        curl_setopt($ch, CURLOPT_COOKIE, $opt['cookie']);

                //Referer
                if(array_key_exists('referer', $opt))
                        curl_setopt($ch, CURLOPT_REFERER, $opt['referer']);

        }else{

                //仅POST
                if(strtoupper((string)$opt) == 'POST')
                        curl_setopt($ch, CURLOPT_POST, true);

        }

        $result = curl_exec($ch);

        if(curl_errno($ch)){
                $result = curl_error($ch);
        }else{

                //获取头长度
                $length = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

                //取出头信息
                $header = substr($result, 0, $length);

                //去掉头信息
                $result = substr($result, $length);

        }

        //释放
        curl_close($ch);

        return $result;

}





class TouClick{
	var $pubkey;
	var $prikey;

	function __construct($pubkey='',$prikey=''){
		$this->pubkey = $pubkey;
		$this->prikey = $prikey;
	}

	/**
	 * @date: 2016-3-23 上午10:20:04
	 * @author : rainbow
	 * @param token 二次验证口令，单次有效
	 * @param checkAddress 二次验证地址，二级域名
	 * @param checkCode 校验码，开发者自定义，一般采用手机号或者用户ID，用来更细致的频次控制
	 * @return :验证成功 或 array(2) { ["code"]=> int(1) ["message"]=> string(23) "二次验证token失效" }
	 */
	public function check($sid, $checkAddress, $token, $userName = '', $userId = 0) {
		if (empty ($checkAddress) || empty ($token) || empty($this->prikey) || empty($this->pubkey)) {
			exit ( '参数为空' );
		}
		if (!preg_match('/^[\w\-]/',$checkAddress)){
			exit('参数格式不正确');
		}
		$params ['s'] = $sid;
		$params ['un'] = $userName;
		$params ['ud'] = $userId;
		$params ['ip'] = @gethostbyname ( $_ENV ['COMPUTERNAME'] );
		$params ['i'] = $token;
		$params ['b'] = $this->pubkey;
		$params ['ran'] = md5(strtotime('now'));
		$sign = $this->getSign ( $params, $this->prikey );
		$params ['sign'] = $sign;
		$paramStr = $this->getStr ( $params );
		$url = "http://" . $checkAddress . ".touclick.com/sverify.touclick2" . '?' . $paramStr;
		// use curl
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_HEADER, 0 );
		$result = curl_exec ( $ch );
		curl_close ( $ch );
		$check = is_object(json_decode($result)) ? get_object_vars(json_decode($result)) : json_decode($result);
		if ($check['code'] == 0) {
			$checkParam['code'] = $check['code'];
			$checkParam['timestamp'] = $params ['ran'];
			$sign = $this->getSign($checkParam, $this->prikey);
			if ($sign == $check['sign']) {
				$res['code'] = 12;
				$res['message'] = '验证成功';
				$res['checkCode'] = $check['ckCode'];
				return $res;
			} else {
				$res['code'] = 12;
				$res['message'] = '签名校验失败,数据可能被篡改';
				return $res;
			}
		} else {
			unset($check['timestamp']);
			unset($check['sign']);
			return $check;
		}
	}

	/**
     * 用户名密码校验后的回调方法
     *
     * @param checkAddress  二次验证地址，二级域名
     * @param token     二次验证口令，单次有效
     * @param sid session id
     * @param isLoginSucc 用户名和密码是否校验成功
     *
     */

	public function callback($sid,$checkAddress,$token,$isLoginSucc){
		if (empty ($checkAddress) || empty ($sid) || empty ($token) || empty($this->prikey) || empty($this->pubkey)) {
			exit ( '参数为空' );
		}
		if (!preg_match('/^[\w\-]/',$checkAddress)){
			exit('参数格式不正确');
		}
		$params ['s'] = $sid;
		$params ['ip'] = @gethostbyname ( $_ENV ['COMPUTERNAME'] );
		$params ['i'] = $token;
		$params ['b'] = $this->pubkey;
		$params ['ran'] = md5(strtotime('now'));
		$params ['su'] = $isLoginSucc ? '1' : '0';
		$sign = $this->getSign ( $params, $this->prikey );
		$params ['sign'] = $sign;
		$paramStr = $this->getStr ( $params );
		$url = "http://" . $checkAddress . ".touclick.com/callback" . '?' . $paramStr;
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_HEADER, 0 );
		curl_exec ( $ch );
		curl_close ( $ch );
	}

	/**
	 * @date: 2016-3-23 上午10:30:15
	 *
	 * @author : rainbow
	 * @param : $params
	 * @param : $prikey
	 * @return :md5($sign)
	 */
	private function getSign($params, $prikey) {
		ksort ( $params ) ? $paramsStr = $this->getStr ( $params ) : exit ( '排序失败' );
		$sign = $paramsStr . $prikey;
		return md5 ( $sign );
	}

	/**
	 * 数组=》字符串 key=value&key=value
	 *
	 * @author : rainbow
	 * @param : $params
	 * @return : $paramsStr
	 */
	private function getStr($params) {
		$paramsStr = '';
		if (! $params || ! is_array ( $params )) {
			exit ( '参数错误' );
		}
		$keys = array_keys ( $params );
		foreach ( $params as $key => $value ) {
			if ($key == end ( $keys )) {
				$paramsStr .= $key . '=' . $value;
			} else {
				$paramsStr .= $key . '=' . $value . '&';
			}
		}
		return $paramsStr;
	}

}